import 'package:flutter/foundation.dart';
import 'package:printing/printing.dart';
import 'dart:typed_data';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;

// 平台无关的打印机接口
abstract class PrinterService {
  Future<void> initialize();
  Future<List<Printer>> findPrinters();
  Future<bool> connect(Printer printer);
  Future<bool> printText(String text, {int fontSize = 12});
  Future<bool> printSimpleChatMessage(String userName, String content, String id);
  
  bool get isConnected;
  String? get printerName;
  
  Function(bool)? onConnectionChanged;
  Function(String)? onError;
}

// iOS 专用的打印机实现
class IOSPrinterService implements PrinterService {
  static final IOSPrinterService _instance = IOSPrinterService._internal();
  factory IOSPrinterService() => _instance;
  IOSPrinterService._internal();

  bool _connected = false;
  String? _printerName;
  int _printCount = 0;

  @override
  Function(bool)? onConnectionChanged;
  @override
  Function(String)? onError;

  @override
  Future<void> initialize() async {
    try {
      if (kIsWeb) {
        _connected = false;
      } else {
        // 在 iOS 上使用 Printing 包
        final canPrint = await Printing.info().then((info) => info.canPrint);
        _connected = canPrint;
        print('[control]设备支持打印功能: $canPrint');
      }
      
      onConnectionChanged?.call(_connected);
    } catch (e) {
      print('[error]打印机初始化错误: $e');
      _connected = false;
      onConnectionChanged?.call(false);
    }
  }

  @override
  Future<List<Printer>> findPrinters() async {
    try {
      if (kIsWeb) {
        return [];
      }
      final printers = await Printing.listPrinters();
      print('[control]找到 ${printers.length} 个打印机');
      return printers;
    } catch (e) {
      print('[error]查找打印机错误: $e');
      onError?.call('查找打印机错误: $e');
      return [];
    }
  }

  @override
  Future<bool> connect(Printer printer) async {
    try {
      _printerName = printer.name;
      _connected = true;
      onConnectionChanged?.call(true);
      print('[control]已连接到打印机: $_printerName');
      return true;
    } catch (e) {
      print('[error]连接打印机错误: $e');
      onError?.call('连接打印机错误: $e');
      return false;
    }
  }

  @override
  Future<bool> printText(String text, {int fontSize = 12}) async {
    if (!_connected) {
      print('[error]打印机未连接');
      onError?.call('打印机未连接');
      return false;
    }

    try {
      // 使用 printing 包打印
      await Printing.layoutPdf(
        onLayout: (format) => _generatePdf(text, fontSize),
        name: '抖音弹幕打印',
      );

      print('[control]已发送到打印机: ${text.length} 字符');
      return true;
    } catch (e) {
      print('[error]打印过程中出错: $e');
      onError?.call('打印错误: $e');
      return false;
    }
  }

  Future<Uint8List> _generatePdf(String text, int fontSize) async {
    final pdf = pw.Document();
    
    pdf.addPage(
      pw.Page(
        pageFormat: PdfPageFormat.roll80,
        build: (pw.Context context) {
          return pw.Column(
            crossAxisAlignment: pw.CrossAxisAlignment.start,
            children: [
              pw.Center(
                child: pw.Text(
                  '抖音弹幕记录',
                  style: pw.TextStyle(
                    fontSize: 16,
                    fontWeight: pw.FontWeight.bold,
                  ),
                ),
              ),
              pw.SizedBox(height: 10),
              pw.Text(
                '时间: ${_getCurrentTime()}',
                style: pw.TextStyle(fontSize: 10),
              ),
              pw.Divider(),
              pw.SizedBox(height: 5),
              pw.Text(
                text,
                style: pw.TextStyle(fontSize: fontSize.toDouble()),
              ),
              pw.SizedBox(height: 5),
              pw.Divider(),
              pw.SizedBox(height: 10),
              pw.Center(
                child: pw.Text(
                  '--- 打印完成 ---',
                  style: pw.TextStyle(
                    fontSize: 10,
                    fontStyle: pw.FontStyle.italic,
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
    
    return pdf.save();
  }

  Future<Uint8List> _generateChatPdf(String formattedMessage) async {
    final pdf = pw.Document();
    
    pdf.addPage(
      pw.Page(
        pageFormat: PdfPageFormat.roll80,
        build: (pw.Context context) {
          return pw.Column(
            crossAxisAlignment: pw.CrossAxisAlignment.start,
            children: [
              pw.Center(
                child: pw.Text(
                  '抖音弹幕记录',
                  style: pw.TextStyle(
                    fontSize: 16,
                    fontWeight: pw.FontWeight.bold,
                  ),
                ),
              ),
              pw.SizedBox(height: 5),
              pw.Text(
                '时间: ${_getCurrentTime()}',
                style: pw.TextStyle(fontSize: 10),
              ),
              pw.Divider(),
              pw.SizedBox(height: 5),
              pw.Text(
                formattedMessage,
                style: pw.TextStyle(fontSize: 12),
              ),
              pw.SizedBox(height: 5),
              pw.Divider(),
              pw.SizedBox(height: 5),
              pw.Center(
                child: pw.Text(
                  '--- 打印完成 ---',
                  style: pw.TextStyle(
                    fontSize: 10,
                    fontStyle: pw.FontStyle.italic,
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
    
    return pdf.save();
  }

  @override
  Future<bool> printSimpleChatMessage(String userName, String content, String id) async {
    if (!_connected) {
      print('[error]打印机未连接');
      onError?.call('打印机未连接');
      return false;
    }

    try {
      // 增加打印计数（需要添加计数变量）
      _printCount++;
      
      // 格式化消息内容，适应小票纸张尺寸
      final formattedMessage = _formatChatMessage(userName, content, id);
      
      // 使用 printing 包打印
      await Printing.layoutPdf(
        onLayout: (format) => _generateChatPdf(formattedMessage),
        name: '抖音弹幕打印',
      );

      print('[control]已发送到打印机: ${content.length} 字符');
      return true;
    } catch (e) {
      print('[error]打印过程中出错: $e');
      onError?.call('打印错误: $e');
      return false;
    }
  }

  String _formatChatMessage(String userName, String content, String userNameI) {
    // 确保所有参数都是字符串
    final userNameStr = userName.isNotEmpty ? userName : "未知用户";
    final contentStr = content.isNotEmpty ? content : "";
    final userNameId = userNameI.isNotEmpty ? userNameI : "";
    
    // 格式化消息内容，适应小票纸张尺寸
    // 纸张尺寸参考：高40mm x 长60mm，大约每行16-20个汉字
    String formattedMessage = "序号: $_printCount\n";
    formattedMessage += "用户名: ${_truncateText(userNameStr, 14)}\n";
    formattedMessage += "用户id: ${_truncateText(userNameId, 14)}\n";
    formattedMessage += "内容:${_truncateText(contentStr, 10)}\n";
  
    formattedMessage += "-" * 16; // 分隔线
    
    return formattedMessage;
  }

  // 文本截断方法
  String _truncateText(String text, int maxLength) {
    if (text.length <= maxLength) {
      return text;
    }
    return text.substring(0, maxLength);
  }

  String _getCurrentTime() {
    final now = DateTime.now();
    return '${now.year}-${_twoDigits(now.month)}-${_twoDigits(now.day)} ${_twoDigits(now.hour)}:${_twoDigits(now.minute)}:${_twoDigits(now.second)}';
  }

  String _twoDigits(int n) => n >= 10 ? "$n" : "0$n";

  @override
  bool get isConnected => _connected;

  @override
  String? get printerName => _printerName;
}

// 空实现用于其他平台
class EmptyPrinterService implements PrinterService {
  @override
  Future<void> initialize() async {
    print('[control]当前平台不支持打印');
  }

  @override
  Future<List<Printer>> findPrinters() async => [];

  @override
  Future<bool> connect(Printer printer) async => false;

  @override
  Future<bool> printText(String text, {int fontSize = 12}) async => false;

  @override
  Future<bool> printSimpleChatMessage(String userName, String content, String id) async => false;

  @override
  bool get isConnected => false;

  @override
  String? get printerName => null;

  @override
  Function(bool)? onConnectionChanged;

  @override
  Function(String)? onError;
}

// 打印机服务工厂
PrinterService createPrinterService() {
  if (defaultTargetPlatform == TargetPlatform.iOS) {
    return IOSPrinterService();
  } else {
    return EmptyPrinterService();
  }
}